<?php

require_once("Dao.php");

/**
 * DAO de l'objet CdrFixeDao.
 * 
 * @author Arthur
 */
class CdrFixeDao extends Dao {

    protected static $tableName = "cdr_fixe";

    /**
     * Liste complète
     */
    public static function getAll() {
        return parent::find(self::$tableName);
    }

    /**
     * Insert un bunch de données dans la table
     * @param array $data
     */
    public static function insertBunch($data) {

        global $bdd;
        global $logger;
        //vidage de la table
        parent::query('DELETE FROM ' . self::$tableName . ' WHERE MONTH(import_date) <> MONTH(NOW());');
        //control que le fichier n'a pas été importé ce mois-ci
        $imported = parent::query("SELECT COUNT(id) count FROM " . self::$tableName . " WHERE type = '" . $data[0]['type'] . "';");
        if ($imported[0]['count'] > 0) {
            return -1;
        }
        try {
            $q     = 'INSERT INTO ' . self::$tableName
                    . ' (id_detail_client, caller_num, called_num, starting_time, duration, type, import_date)'
                    . ' VALUES ';
            $qPart = array_fill(0, count($data), "(?, ?, ?, ?, ?, ?, ?)");
            $q .= implode(",", $qPart) . ';';
            $stmt  = $bdd->prepare($q);
            $i     = 1;
            $now   = new DateTime('now');
            foreach ($data as $item) { //bind the values one by one
                $stmt->bindParam($i++, $item['id_detail_client']);
                $stmt->bindParam($i++, $item['caller_num']);
                $stmt->bindParam($i++, $item['called_num']);
                $stmt->bindParam($i++, $item['starting_time']->format('Y-m-d H:i:s'));
                $stmt->bindParam($i++, $item['duration']);
                $stmt->bindParam($i++, $item['type']);
                $stmt->bindParam($i++, $now->format('Y-m-d'));
            }
            $bdd->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
            return $stmt->execute();
        } catch (PDOException $e) {
            echo $e->getMessage();
        }
    }

}
